package main

import (
	"flag"
	"fmt"
	"gitee.com/madaoco/cron_node/rpc/server"
	"gitee.com/madaoco/cron_node/utils"
	"log"
	"os"
	"runtime"
)

var (
	serverAddr string
	allowRoot  bool
	version    bool
	CAFile     string
	certFile   string
	keyFile    string
	enableTLS  bool
	logLevel   string
)

//init
func init() {
	flag.BoolVar(&allowRoot, "allow-root", true, "./cron-node -allow-root")
	flag.StringVar(&serverAddr, "s", "0.0.0.0:5000", "./cron-node -s ip:port")
	flag.BoolVar(&version, "v", false, "./cron-node -v")
	flag.BoolVar(&enableTLS, "enable-tls", false, "./cron-node -enable-tls")
	flag.StringVar(&CAFile, "ca-file", "E:\\code\\go\\cron_node\\cert\\RootCA.crt", "./cron-node -ca-file path")
	flag.StringVar(&certFile, "cert-file", "E:\\code\\go\\cron_node\\cert\\NodeServer.crt", "./cron-node -cert-file path")
	flag.StringVar(&keyFile, "key-file", "E:\\code\\go\\cron_node\\cert\\NodeServer.key", "./cron-node -key-file path")
	//todo 增加log文件记录
	flag.StringVar(&logLevel, "log-level", "info", "-log-level error")
}

// main
func main() {
	flag.Parse()
	if version {
		fmt.Println("v1.0.0")
		return
	}

	if runtime.GOOS != "windows" && os.Getuid() == 0 && !allowRoot {
		log.Fatalln("Do not run  cron node as root user")
	}
	fmt.Println(CAFile)
	if enableTLS {
		if !utils.FileExist(CAFile) {
			log.Fatalf("failed to read ca cert file: %s", CAFile)
		}
		if !utils.FileExist(certFile) {
			log.Fatalf("failed to read server cert file: %s", certFile)
			return
		}
		if !utils.FileExist(keyFile) {
			log.Fatalf("failed to read server key file: %s", keyFile)
			return
		}
	}
	tlsConfig := server.TlsConfig{
		EnableTLS: enableTLS,
		RootCA:    CAFile,
		CertFile:  certFile,
		KeyFile:   keyFile,
	}
	server.Start(serverAddr, &tlsConfig)
}
